package com.zhuimeng.minicat.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {
    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            if (request.getUrl().equalsIgnoreCase("/favicon.ico")){
                return;
            }
            String contextName = request.getUrl().split("/")[1];
            String path = "/" + request.getUrl().split("/")[2];
            Mapper.Wrapper wrapper = mapper.getHostMap().get("localhost").getContextMap().get(contextName).getWrapperMap().get(path);
            if (wrapper == null){
                String localPath = mapper.getHostMap().get("localhost").getAppBase() + request.getUrl();
                response.outputHtml(localPath);
            }else {
                wrapper.getHttpServlet().service(request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
